package com.jwm.platform;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.jwm.model.*;
import com.jwm.model.ServiceVo;
import com.jwm.util.AjaxResult;
import com.jwm.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 崔洁
 */
@RestController
public class ReceiveController {
    private static final Logger logger = LoggerFactory.getLogger(ReceiveController.class);
    @Resource
    private PlteData plteData;
    @Resource
    private PlatformConfig platformConfig;

    @RequestMapping(method = RequestMethod.POST, path = "/jwm/heartbeat")
    @ResponseBody
    public String heartbeat(String name) {
        logger.info("平台端 => 收到心跳：{}", name);
        List<ClientVo> clientVoList = plteData.getClientVoList();
        List<ClientVo> clientVoThis = clientVoList.stream().filter(clientVo -> clientVo.getName().equals(name)).collect(Collectors.toList());
        ClientVo clientVo;
        if (clientVoThis.size() == 0) {
            clientVo = new ClientVo(name, DateUtils.dateTimeNow(), 1);
            clientVoList.add(clientVo);
        } else {
            clientVo = clientVoThis.get(0);
            clientVo.setTime(DateUtils.dateTimeNow());
            clientVo.setState(1);
        }
        String commond = clientVo.getCommond();
        clientVo.setCommond("");
        logger.info("平台端 => 心跳返回：{}", commond);
        return commond;
    }

    @RequestMapping(method = RequestMethod.POST, path = "/jwm/getComputer")
    @ResponseBody
    public void getComputer(@RequestBody Computer computer, @RequestParam("name") String name) {
        logger.info("平台端 => 收到 {} computer信息：{}", name, JSONUtil.toJsonStr(computer));
        List<ClientVo> clientVoList = plteData.getClientVoList();
        List<ClientVo> clientVoThis = clientVoList.stream().filter(clientVo -> clientVo.getName().equals(name)).collect(Collectors.toList());
        if (clientVoThis.size() > 0) {
            clientVoThis.get(0).setComputer(computer);
        }
    }

    @RequestMapping(method = RequestMethod.POST, path = "/jwm/getSysFiles")
    @ResponseBody
    public void getSysFiles(@RequestBody List<SysFile> vos, @RequestParam("name") String name) {
        logger.info("平台端 => 收到 {} SysFile信息：{}", name, JSONUtil.toJsonStr(vos));
        List<ClientVo> clientVoList = plteData.getClientVoList();
        List<ClientVo> clientVoThis = clientVoList.stream().filter(clientVo -> clientVo.getName().equals(name)).collect(Collectors.toList());
        if (clientVoThis.size() > 0) {
            clientVoThis.get(0).setSysFiles(vos);
        }
    }

    @RequestMapping(method = RequestMethod.POST, path = "/jwm/getTomcats")
    @ResponseBody
    public void getTomcats(@RequestBody List<TomcatVo> vos, @RequestParam("name") String name) {
        logger.info("平台端 => 收到 {} Tomcat信息：{}", name, JSONUtil.toJsonStr(vos));
        List<ClientVo> clientVoList = plteData.getClientVoList();
        List<ClientVo> clientVoThis = clientVoList.stream().filter(clientVo -> clientVo.getName().equals(name)).collect(Collectors.toList());
        if (clientVoThis.size() > 0) {
            clientVoThis.get(0).setTomcatVos(vos);
        }
    }

    @RequestMapping(method = RequestMethod.POST, path = "/jwm/getJars")
    @ResponseBody
    public void getJars(@RequestBody List<JarVo> vos, @RequestParam("name") String name) {
        logger.info("平台端 => 收到 {} Jar信息：{}", name, JSONUtil.toJsonStr(vos));
        List<ClientVo> clientVoList = plteData.getClientVoList();
        List<ClientVo> clientVoThis = clientVoList.stream().filter(clientVo -> clientVo.getName().equals(name)).collect(Collectors.toList());
        if (clientVoThis.size() > 0) {
            clientVoThis.get(0).setJarVos(vos);
        }
    }

    @RequestMapping(method = RequestMethod.POST, path = "/jwm/getServices")
    @ResponseBody
    public void getServices(@RequestBody List<ServiceVo> vos, @RequestParam("name") String name) {
        logger.info("平台端 => 收到 {} Service信息：{}", name, JSONUtil.toJsonStr(vos));
        List<ClientVo> clientVoList = plteData.getClientVoList();
        List<ClientVo> clientVoThis = clientVoList.stream().filter(clientVo -> clientVo.getName().equals(name)).collect(Collectors.toList());
        if (clientVoThis.size() > 0) {
            clientVoThis.get(0).setServiceVos(vos);
        }
    }

    @RequestMapping(method = RequestMethod.POST, path = "/jwm/getBats")
    @ResponseBody
    public void getBats(@RequestBody List<BatVo> vos, @RequestParam("name") String name) {
        logger.info("平台端 => 收到 {} Bat信息：{}", name, JSONUtil.toJsonStr(vos));
        List<ClientVo> clientVoList = plteData.getClientVoList();
        List<ClientVo> clientVoThis = clientVoList.stream().filter(clientVo -> clientVo.getName().equals(name)).collect(Collectors.toList());
        if (clientVoThis.size() > 0) {
            clientVoThis.get(0).setBatVos(vos);
        }
    }

    @RequestMapping(method = RequestMethod.POST, path = "/jwm/cmdSuccess")
    @ResponseBody
    public AjaxResult cmdSuccess(@RequestBody CmdInfoVo cmdInfoVo) {
        logger.info("平台端 => 收到命令执行成功信息：{}", JSONUtil.toJsonStr(cmdInfoVo));
        for (int i = 0; i < plteData.getCmdingList().size(); i++) {
            CmdInfoVo cmdingMap = plteData.getCmdingList().get(i);
            if (cmdingMap.getId().equals(cmdInfoVo.getId())) {
                BeanUtil.copyProperties(cmdInfoVo, cmdingMap);
                cmdingMap.setReturnStr(cmdInfoVo.getReturnStr());
                break;
            }
        }
        return AjaxResult.success();
    }

    @RequestMapping(method = RequestMethod.POST, path = "/jwm/uploadFile")
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam MultipartFile file, String cmdId) {
        logger.info("上传文件命令完成：{}", cmdId);
        for (int i = 0; i < plteData.getCmdingList().size(); i++) {
            CmdInfoVo cmdingMap = plteData.getCmdingList().get(i);
            if (cmdingMap.getId().equals(cmdId)) {
                File uploadFile = new File(platformConfig.getFileTempPath());
                //判断文件目录是否存在 如果不存在，就创建一个文件夹
                if (!uploadFile.exists()) {
                    uploadFile.mkdirs();
                }
                //使用文件IO获取到文件
                String fileName = platformConfig.getFileTempPath() + file.getOriginalFilename();
                logger.info("上传文件保存：{}", fileName);
                File uploadFiles = new File(fileName);
                //把文件存储到磁盘目录 抛出IO异常
                try {
                    file.transferTo(uploadFiles);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("上传文件命令失败\n{}", e);
                }
                cmdingMap.setReturnStr("/profile/" + file.getOriginalFilename());
                break;
            }
        }
        return AjaxResult.success();
    }
}
